package com.chenfan.mcn.rule;

import com.chenfan.mcn.extension.rule.ComputableRule;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.ObjectUtils;

import java.math.BigDecimal;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * 均摊个税计算规则
 * @author wulg
 * @date 2022-01-14
 **/
public class ShareTaxAmountRule implements ComputableRule<ShareTaxAmountContext, Map<Long, BigDecimal>> {

    @Override
    public Map<Long, BigDecimal> execute(ShareTaxAmountContext context) {
        //税前金额
        BigDecimal pretaxAmount = ObjectUtils.defaultIfNull(context.getPretaxAmount(), BigDecimal.ZERO);

        //应扣税额
        BigDecimal taxableAmount = ObjectUtils.defaultIfNull(context.getTaxableAmount(), BigDecimal.ZERO);

        //K：执行单ID V：该执行单-执行单财务确认分成金额
        Map<Long, BigDecimal> devidedMap = context.getDevidedMap();

        if(MapUtils.isEmpty(devidedMap)) {
            return devidedMap;
        }
        if(pretaxAmount.compareTo(BigDecimal.ZERO) == 0 || taxableAmount.compareTo(BigDecimal.ZERO) == 0) {
            Map<Long, BigDecimal> shareTaxMap = new LinkedHashMap<>(devidedMap.size());
            devidedMap.forEach((k,v) -> {
                shareTaxMap.put(k, BigDecimal.ZERO);
            });
            return shareTaxMap;
        }
        BigDecimal ratio = taxableAmount.divide(pretaxAmount, 12 , BigDecimal.ROUND_HALF_UP);
        Map<Long, BigDecimal> shareTaxMap = new LinkedHashMap<>(devidedMap.size());
        BigDecimal accruedAmount = BigDecimal.ZERO;
        Iterator<Map.Entry<Long, BigDecimal>> iterator = devidedMap.entrySet().iterator();
        while (iterator.hasNext()) {
            Map.Entry<Long, BigDecimal> entry = iterator.next();
            if(iterator.hasNext()) {
                BigDecimal shareTaxAmount = ObjectUtils.defaultIfNull(entry.getValue(), BigDecimal.ZERO).multiply(ratio).setScale(2, BigDecimal.ROUND_HALF_UP);
                accruedAmount = accruedAmount.add(shareTaxAmount);
                shareTaxMap.put(entry.getKey(), shareTaxAmount);
            } else {
                shareTaxMap.put(entry.getKey(), taxableAmount.subtract(accruedAmount));
            }
        }
        return shareTaxMap;
    }

    /*public static void main(String[] args) {
        ShareTaxAmountContext context = new ShareTaxAmountContext();
        context.setPretaxAmount(new BigDecimal("60300.69"));
        context.setTaxableAmount(new BigDecimal("300"));
        Map<Long, BigDecimal> devidedMap = new LinkedHashMap<>();
        devidedMap.put(1L, new BigDecimal("60000"));
        devidedMap.put(2L, new BigDecimal("300.69"));
        context.setDevidedMap(devidedMap);
        Map<Long, BigDecimal> resultMap = ComputableRuleEngine.fire(ShareTaxAmountRule.class, context);
        System.out.println(resultMap);
    }*/
}
